<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ include file="/include/taglibs.jsp" %>
<title>用户管理</title>
<link rel="stylesheet" href="${ctx}/assets/admin/LingUI/css/jquery-ui.min.css"/>
<link rel="stylesheet" href="${ctx}/assets/admin/LingUI/css/ui.jqgrid.css"/>
<link rel="stylesheet" href="${ctx}/css/base.css"/>
<script type="text/javascript" src="${ctx}/assets/admin/LingUI/js/ztree/js/jquery.ztree.core-3.5.js"></script>
<!-- 树插件核心 -->
<script type="text/javascript" src="${ctx}/assets/admin/LingUI/js/ztree/js/jquery.ztree.exedit-3.5.js"></script>
<!-- 树编辑插件 -->
<script type="text/javascript" src="${ctx}/assets/uc/js/common.js"></script>
<div class="row xtgltree">
    <input type="text" id="selectDepId" style="display:none"/>
    <div class="col-sm-3">
        <div class="widget-box widget-color-blue2" style="height:600px;min-height:420px; height:auto!important">
            <div class="widget-header">
                <h4 class="widget-title lighter smaller">部门列表</h4>
            </div>
            <div class="widget-body">
                <div class="widget-main padding-8">
                    <div class="zTreeDemoBackground">
                        <ul id="treeDemo" class="ztree"></ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-sm-9">
        <div class="widget-box " style="height:600px;min-height :420px; height:auto!important">
            <div class="widget-header">
                <h4 class="widget-title lighter smaller">用户列表</h4>
            </div>


            <div id="search" style="height: 100px;">
                <form class="form-horizontal" role="form" id="role_form">
                    <div class="tabbable">
                        <div class="profile-user-info profile-user-info-striped" style="padding:0px;margin:0px;width:100%;">
                            <div class="profile-info-row">
                                <div class="profile-info-name">名称：</div>
                                <div class="profile-info-value">
                                    <input id="USER_NAME" name="USER_NAME" type="text"
                                           style="width:200px;">
                                </div>
                            </div>

                                <div class="profile-info-row">
                                    <div class="profile-info-name">角色：</div>
                                    <div class="profile-info-value">
                                        <select type="text" id="ROLE_ID" name="ROLE_ID" style="width:200px;"
                                                class=" form-control col-xs-10 col-sm-8">
                                        </select>
                                    </div>
                                </div>

                        </div>

                        <div class="profile-info-row"
                             style="width:100%;text-align:center;margin-top:10px;margin-bottom:0px;border:0px;">
                            <div class="field_item mcenter">
                                <input type="submit" class="chaxun" id="J_search" value="查询">
                                <input type="reset" class="chongzhi" id="J_reset" value="重置">
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <%--查询条件更多 --%>
            <div class="b_grid_line  col-lg-12"></div>
            <div class="widget-body">
                <div class="widget-main padding-8 admin-body">
                    <table id="admin_table"></table>
                    <div id="admin_pager"></div>
                </div>
            </div>
        </div>
    </div>

</div>

<script type="text/javascript">
    //导入脚本
    var scripts = [null,
        "${ctx}/assets/admin/LingUI/js/jqGrid/jquery.jqGrid.js",
        "${ctx}/assets/admin/LingUI/js/jqGrid/i18n/grid.locale-cn.js",
        "${ctx}/assets/admin/LingUI/js/control.js",
        "${ctx}/assets/admin/LingUI/js/jsutil/js/jquery.filterSearch.js",
        null];

    /**
     * 设置全局变量
     */
    var tree = "treeDemo";//树id
    var $tree = $("#treeDemo");
    var zTree; //树对象

    var _grid_id = "#admin_table";	//表格 选择器
    var _pager_id = "#admin_pager";	//表格页脚 选择器
    var url = "${ctx}/${frameworkPath}/user/index?sort=USER_CREATED&&dir=asc"; //表格url

    ace.load_ajax_scripts(scripts, function () {
        $('#J_reset').on('click', function (e) {
            e.preventDefault();

            $('#ROLE_ID').val('');
            $('#USER_NAME').val('');
            var USER_NAME = '';
            var ROLE_ID = '';

            var data = {
                "USER_NAME": USER_NAME,
                "ROLE_ID": ROLE_ID
            };

            jQuery("#admin_table").jqGrid('setGridParam', {
                url: url,
                mtype: "POST",
                postData: data //传递的数据
            }).trigger("reloadGrid");
        });
        //查询按钮压下触发函数
        $('#J_search').on('click', function (e) {
            e.preventDefault();
            var ROLE_ID = $('#ROLE_ID').val();
            var USER_NAME = $('#USER_NAME').val();

            var data = {
                "USER_NAME": USER_NAME,
                "ROLE_ID": ROLE_ID
            };

            jQuery("#admin_table").jqGrid('setGridParam', {
                url: url,
                mtype: "POST",
                postData: data //传递的数据
            }).trigger("reloadGrid");

        });
        jQuery(function ($) {
            $('input, textarea').placeholder(); //空输入框中占位符
            loadRoles();
            $('#ROLE_ID').val('');
            var setting = {
                async: {
                    autoParam: ["id=id"],
                    enable: true,
                    type: "GET",
                    dataType: 'json',
                    url: "${ctx}/${frameworkPath}/org/children"
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: onClick,				//树节点点击事件
                    onAsyncSuccess: zTreeOnAsyncSuccess
                }
            };

         /*   $("#search").strongFilterSearch({
                inputFiled: "USER_ID",				//搜索字段，不填默认为searchValue
                inputPlaceholder: "请输入用户帐号等关键字",		//占位符
                searchCallback: callback//,				//搜索按钮点击后回调
            });
            //搜索回调函数
            function callback(data) {
                jQuery(_grid_id).jqGrid('setGridParam', {
                    url: url,
                    mtype: "POST",
                    postData: data //传递的数据
                }).trigger("reloadGrid");
            }*/

            zTree = $.fn.zTree.init($tree, setting); //树初始化

            //调整以适应页面大小  其中 $(".page-content") 为jqgrid的父级容器
            $(window).off('resize.jqGrid').on('resize.jqGrid', function () {
                setTimeout(function () {
                    $(_grid_id).jqGrid("setGridWidth", $(".admin-body").width());
                    $(".ui-jqgrid-bdiv").width($(".admin-body").width() + 1);
                }, 50);
            });

            jQuery(_grid_id).jqGrid({
                url: url,
                postData: {
                    org: 1//相当于不查询
                },
                colNames: ['账号', '姓名', '邮箱', '状态','审核状态'],
                colModel: [
                    {name: 'username', index: 'username', key: true, width: 30, hidden: false},
                    {name: 'name', index: 'name', width: 50},
                    {name: 'email', index: 'email', width: 60, align: 'left'},
                  /*  {name: 'post', index: 'post', width: 40, align: 'left', hidden:true},*/
                    {
                        name: 'enabled', index: 'enable', width: 20, align: 'center'
                        , formatter: function (cellvalue, options, rowObject) {
                        if (cellvalue == true) {
                            return "<span class='label  label-success'>启用</span>";
                        } else {
                            return "<span class='label  label'>禁用</span>";
                        }
                    }},
                    {
                        name: 'roleId', index: 'roleId', width: 20, align: 'center'
                        , formatter: function (cellvalue, options, rowObject) {
                        if (cellvalue == "NEW_REGISTER") {
                            return "<span class='label  label-warning'>未审核</span>";
                        } else {
                            return "<span class='label  label-success'>已审核</span>";
                        }
                    }
                    }
                ],
                pager: _pager_id //分页信息 放置的位置
            });

            var jqgridButton = jQuery(_grid_id).jqGrid('navGrid', _pager_id);

           /* <shiro:hasPermission name="USER_CREATE">
            jqgridButton.navButtonAdd(_pager_id, {
                title: "新增",//按钮悬浮提示
                buttonicon: "ace-icon fa fa-plus-circle purple",//按钮图标和颜色
                onClickButton: addrows //点击按钮响应方法
            })
            </shiro:hasPermission>*/
            <shiro:hasPermission name="USER_EDIT">
             jqgridButton.navButtonAdd(_pager_id, {
             title: "编辑",//按钮悬浮提示
             buttonicon: "ace-icon fa fa-pencil purple",//按钮图标和颜色
             onClickButton: editrows //点击按钮响应方法
             })
            </shiro:hasPermission>

          /*  <shiro:hasPermission name="USER_DELETE">
            jqgridButton.navButtonAdd(_pager_id, {
                title: "删除",
                buttonicon: "ace-icon fa fa-trash-o red",
                onClickButton: function () {
                    var idArr = $(_grid_id).jqGrid("getGridParam", "selarrrow");//获取所有选中行的id字符串
                    if (idArr.length == 0) {
                        lui.info("请选择一条记录！");
                        return;
                    }
                    else {
                        var rowDataArr = $(_grid_id).jqGrid("getRowDataArr");//获取所有选中的row 的数据数组
                        for (var i in rowDataArr) {
                            var rowData = rowDataArr[i];
                            if (rowData["enabled"].indexOf("启用") != -1) {
                                lui.info("账号[" + rowData['username'] + "]为有效客户不能被删除！");
                                return;
                            }
                        }
                        lui.confirm("确定删除所选记录吗？"
                                , function () {
                                    deleteUsers(idArr);
                                }, function () {

                                });
                    }
                }
            })
            </shiro:hasPermission>*/

            jqgridButton.navButtonAdd(_pager_id, {
                title: "刷新",
                buttonicon: "ace-icon fa fa-refresh orange",
                onClickButton: function () {
                    reloadGrid();
                }
            })

            jqgridButton.navButtonAdd(_pager_id, {
                title: "审核",
                iconTitle: "审核",
                buttonicon: "ace-icon fa fa-play red",
                onClickButton: function () {
                    var idArr = $(_grid_id).jqGrid("getGridParam", "selarrrow");//获取所有选中行的id字符串
                    var rowData = $(_grid_id).jqGrid("getRowData", idArr[0]);
                    var val = rowData.roleId;
                    debugger;
                    if (idArr.length == 0) {
                        lui.info("请选择一条记录！")
                        return;
                    }else   if (idArr.length >1) {
                        lui.info("只能选择一条记录！")
                        return;
                    } else  if (val == '<span class="label  label-success">已审核</span>'){
                        lui.info("只有未审核用户可以启用！")
                        return;
                    }

                    else {
                        approveUser(idArr);
                    }
                }
            })

            <shiro:hasPermission name="USER_ENABLE">
            jqgridButton.navButtonAdd(_pager_id, {
                title: "启用",
                iconTitle: "启用",
                buttonicon: "ace-icon fa  fa-unlock green",
                onClickButton: function () {
                    var idArr = $(_grid_id).jqGrid("getGridParam", "selarrrow");//获取所有选中行的id字符串
                    if (idArr.length == 0) {
                        lui.info("请选择一条记录！")
                        return;
                    }else   if (idArr.length >1) {
                        lui.info("只能选择一条记录！")
                        return;
                    }

                    else {
                        enableUser(idArr);
                    }
                }
            })
            </shiro:hasPermission>
         <shiro:hasPermission name="USER_DISABLE">
            jqgridButton.navButtonAdd(_pager_id, {
                title: "禁用",
                iconTitle: "禁用",
                buttonicon: "ace-icon fa  fa-lock red",
                onClickButton: function () {
                    var idArr = $(_grid_id).jqGrid("getGridParam", "selarrrow");//获取所有选中行的id字符串
                    if (idArr.length == 0) {
                        lui.info("请选择一条记录！")
                        return;
                    }
                    else {
                        disableUser(idArr);
                    }
                }
            })
            </shiro:hasPermission>

            <shiro:hasPermission name="USER_ROLE">
            jqgridButton.navButtonAdd(_pager_id, {
                title: "分配角色",
                buttonicon: "ace-icon fa fa-users green",
                onClickButton: function () {
                    var idArr = $(_grid_id).jqGrid("getGridParam", "selarrrow");//获取所有选中行的id字符串
                    if (idArr.length == 0) {
                        lui.info("请选择一条记录！")
                        return;
                    }
                    else if (idArr.length > 1) {
                        lui.info("最多选择一条记录！")
                        return;
                    }
                    else {
                        lui.open({
                            title: "分配角色",
                            content: '${ctx}/${frameworkPath}/user/role?username=' + idArr[0],
                           // content: '${ctx}/${frameworkPath}/user/role,
                            area: ["60%", "500px"],
                            yes: function (index, layero) {
                                var retObj = $(layero).find("iframe")[0].contentWindow.submit();
                                if (retObj && retObj.text) {
                                    lui.info(retObj.text);
                                    if (retObj.state) {
                                        layer.close(index);
                                        reloadGrid({
                                            org: $("#selectDepId").val()
                                        });
                                    }
                                }
                            }
                        });
                    }
                }
            })
            </shiro:hasPermission>
            jqgridButton.navButtonAdd(_pager_id, {
                title: "重置密码",
                buttonicon: "ace-icon fa fa-key",
                onClickButton: function () {
                    var idArr = $(_grid_id).jqGrid("getGridParam", "selarrrow");//获取所有选中行的id字符串
                    if (idArr.length == 0) {
                        lui.info("请选择一条记录！");
                        return;
                    }
                    else if (idArr.length > 1) {
                        lui.info("最多选择一条记录！");
                        return;
                    }
                    lui.confirm("确定要重置所选用户的密码吗？"
                            , function () {
                                resetPassword(idArr);
                            }, function () {

                            });
                }
            }).navSeparatorAdd()
      /*      jqgridButton.navButtonAdd( _pager_id,{
                title : "导入用户",
                buttonicon : "ace-icon fa fa-cloud-upload",
                onClickButton : function(){
                    lui.open({
                        title: "导入用户",
                        content: "${ctx}/${frameworkPath}/user/import?orgId=" + $("#selectDepId").val(),
                        area: ["50%", "450px"],
                        btnAlign: 'c',
                        yes: function (index, layero) {
                            var retObj = $(layero).find("iframe")[0].contentWindow.formValid();
                            if (retObj) {
                                lui.info(retObj.text);
                                if (retObj.state) {
                                    layer.close(index);
                                    reloadGrid({
                                        org: $("#selectDepId").val()
                                    });
                                }
                            }
                            else {
                                lui.close(mask);
                            }
                        }
                    });
                }
            });*/
        });
    });

    /**
     * 表格刷新
     */
    function reloadGrid(data) {
        jQuery(_grid_id).jqGrid('setGridParam', {
            url: url,
            postData: data //传递的数据
        }).trigger("reloadGrid");
    }
    /**
     * 新增用户
     */
    function addrows() {
        lui.open({
            title: "添加用户",
            content: "${ctx}/${frameworkPath}/user/create?org=" + $("#selectDepId").val(),
            area: ["50%", "450px"],
            yes: function (index, layero) {
                var retObj = $(layero).find("iframe")[0].contentWindow.formValid();
                if (retObj && retObj.text) {
                    lui.success(retObj.text);
                    if (retObj.state) {
                        layer.close(index);
                        reloadGrid({
                            org: $("#selectDepId").val()
                        });
                    }
                }
            }
        });

        //toLocation("#sf/user/create")
    }
    //加载角色
    function loadRoles() {
        $.ajax({
            type: 'POST',
            url: '${ctx}/${frameworkPath}/role/index?page=1&sort=ROLE_ORDER&&dir=asc',
            async: false,
            dataType: 'json',
            success: function (data) {
                var tempAjax = "";
                $.each(data.rows, function (idx, item) {
                    tempAjax += "<option value='" + item.id + "'>" + item.name + "</option>";
                });
                $("#ROLE_ID").empty();
                $("#ROLE_ID").html(tempAjax);
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) {
                lui.fail('加载数据失败！');
            }
        });
    }
    /**
     * 编辑
     */
    function editrows() {
        var idArr = $('#admin_table').jqGrid("getGridParam", "selarrrow");//获取所有选中行的id字符串
        if (idArr.length == 0) {
            lui.info("请选择一条记录！");
            return;
        }
        else if (idArr.length > 1) {
            lui.info("最多选择一条记录！");
            return;
        }
        lui.open({
            title: "账号信息",
            content: "${base}/sf/user/edit?id=" + idArr[0],
            area: ["50%", "450px"],
            yes: function (index, layero) {
                var retObj = $(layero).find("iframe")[0].contentWindow.formValid();
                if (retObj) {
                    lui.info(retObj.text);
                    if (retObj.state) {
                        layer.close(index);
                        reloadGrid({
                            depId: $("#selectDepId").val()
                        });
                    }
                }
            }
        });
    }

    /**
     * 表格删除
     */
    function deleteUsers(ids) {
        var selectDepId = $("#selectDepId").val();
        var idArray = new Array();
        for (var i = 0; i < ids.length; i++) {
            idArray.push(ids[i]);
        }
        $.ajax({
            type: 'POST',
            url: '${ctx}/${frameworkPath}/user/delete',
            traditional: true,
            dataType: 'json',
            data: {'usernames': idArray, _method: 'delete'},
            success: function (message) {
                if (message.success) {
                    lui.success('删除成功');
                    reloadGrid({
                        org: selectDepId
                    });
                }
                else {
                    lui.fail(message.error);
                }
            }
        });
    }

    function disableUser(ids) {
        var selectDepId = $("#selectDepId").val();
        var idArray = new Array();
        for (var i = 0; i < ids.length; i++) {
            idArray.push(ids[i]);
        }
        $.ajax({
            type: 'POST',
            url: '${ctx}/${frameworkPath}/user/disable',
            traditional: true,
            dataType: 'json',
            data: {'usernames': idArray},
            success: function (data) {
                if (data.success) {
                    lui.success("操作成功");
                    reloadGrid({
                        org: $("#selectDepId").val()
                    });
                }
                else {
                    lui.fail("操作失败");
                }
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) {
                lui.fail("操作失败:" + XmlHttpRequest.status);
            }
        });
    }
    function approveUser(ids) {
        var selectDepId = $("#selectDepId").val();
        var idArray = new Array();
        for (var i = 0; i < ids.length; i++) {
            idArray.push(ids[i]);
        }
        $.ajax({
            type: 'POST',
            url: '${ctx}/${frameworkPath}/user/enable2',
            traditional: true,
            dataType: 'json',
            data: {'usernames': idArray},
            success: function (data) {
                if (data.success) {
                    lui.success("操作成功");
                    reloadGrid({
                        org: $("#selectDepId").val()
                    });
                }
                else {
                    lui.fail("操作失败");
                }
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) {
                lui.fail("操作失败:" + XmlHttpRequest.status);
            }
        });
    }

    function enableUser(ids) {
        var selectDepId = $("#selectDepId").val();
        var idArray = new Array();
        for (var i = 0; i < ids.length; i++) {
            idArray.push(ids[i]);
        }
        $.ajax({
            type: 'POST',
            url: '${ctx}/${frameworkPath}/user/enable',
            traditional: true,
            dataType: 'json',
            data: {'usernames': idArray},
            success: function (data) {
                if (data.success) {
                    lui.success("操作成功");
                    reloadGrid({
                        org: $("#selectDepId").val()
                    });
                }
                else {
                    lui.fail("操作失败");
                }
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) {
                lui.fail("操作失败:" + XmlHttpRequest.status);
            }
        });
    }

    /**
     * 转移部门
     */
    function transferDept(ids) {
        lui.open({
            title: "转移部门",
            content: "${base}/admin/user/deptree.do",
            area: ["400px", "400px"],
            yes: function (index, layero) {
                var idArr = $(_grid_id).jqGrid("getGridParam", "selarrrow");//获取所有选中行的id字符串
                var dept = $(layero).find("iframe")[0].contentWindow.getDept();
                var ids = lui.arrayToString(idArr);
                $.ajax({
                    url: "${base}/admin/user/transferDept.do",
                    type: "post",
                    dataType: 'json',
                    data: {
                        id: lui.arrayToString(idArr),
                        depId: dept["id"]
                    },
                    success: function (text) {
                        if (text == "success") {
                            lui.info("转移部门成功！");
                            lui.close(index);
                            reloadGrid({
                                org: $("#selectDepId").val()
                            });
                        } else {
                            lui.info(text);
                        }
                    }
                });
            }
        });
    }

    /**
     *    树节点点击事件
     */
    function onClick(event, treeId, treeNode, clickFlag) {
        $("#selectDepId").val(treeNode.id);
        var data = {
            org: treeNode.id
        }
        reloadGrid(data); //员工表格刷新
    }

    var zTreeOnAsyncSuccess = function () {

        asyncNodes(zTree.getNodes());
        zTree.expandAll(true);

        //select root node
        var node = zTree.getNodes()[0];
        zTree.selectNode(node);
        zTree.setting.callback.onClick(null, zTree.setting.treeId, node);
    }

    function asyncNodes(nodes) {
        if (!nodes) return;
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        for (var i = 0, l = nodes.length; i < l; i++) {
            if (nodes[i].isParent && nodes[i].zAsync) {
                asyncNodes(nodes[i].children);
            }
            else {
                zTree.reAsyncChildNodes(nodes[i], "refresh", true);
            }
        }
    }

    function resetPassword(ids) {
        var idArray = new Array();
        for (var i = 0; i < ids.length; i++) {
            idArray.push(ids[i]);
        }
        $.ajax({
            type: 'POST',
            url: '${ctx}/${frameworkPath}/user/resetpassword',
            traditional: true,
            dataType: 'json',
            data: {'usernames': idArray},
            success: function (data) {
                if (data.success) {
                    lui.success("重置密码成功")
                }
                else {
                    lui.success("重置密码失败")
                }
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) {
                lui.success("重置密码失败")
            }
        });
    }
    ;

</script>
